package com.xfan.core.web;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.xfan.core.Constants;
import com.xfan.core.util.JsonUtil;

public class BaseAction<T extends BaseDao> extends ActionSupport implements Preparable{
	private static final long serialVersionUID = -4540062085613373278L;
	protected Map<String,Object> sysParam=new HashMap<String,Object>();
	protected T dao;
	public T getDao() {
		return dao;
	}
	public void setDao(T dao) {
		this.dao = dao;
	}
	public void prepare() throws Exception {
		// TODO 常用系统参数设置
		sysParam.put("userId", "");
	}
	
	/**
	 * 直接获取参数
	 * @param name
	 * @return
	 */
	public String $(String name){
		return ServletActionContext.getRequest().getParameter(name);
	}
	
	/**
	 * 直接输出.
	 * 
	 * @param contentType 内容的类型.html,text,xml的值见后，json为"text/x-json;charset=UTF-8"
	 */
	protected void render(String text,String contentType){
		HttpServletResponse response = ServletActionContext.getResponse();
		try {
			response.setContentType(contentType+";charset"+Constants.PAGE_ENCODE);
			response.getWriter().write(text);
		} catch (IOException e) {
			//log.error(e.getMessage(), e);
		}
	}

	/**
	 * 直接输出纯字符串.
	 */
	protected void renderText(String text) {
		render(text,"text/plain");
	}

	/**
	 * 直接输出纯HTML.
	 */
	protected void renderHtml(String text) {
		render(text,"text/html");
	}

	/**
	 * 直接输出纯XML.
	 */
	protected void renderXML( String text) {
		render(text,"text/xml");
	}
	
	/**
	 * 直接输出JSON.
	 */
	protected void renderJson(Object obj) {
		renderText(JsonUtil.getJson(obj));
	}
}
